
package mission2.dao;

import java.util.List;

import mission2.entity.User;
import mission2.util.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;



public class UserDAOImpl implements UserDao{
	Session session =null;
	
	
	public boolean doCreate(User user) throws Exception {
		
		try{
			
			session =HibernateUtil.getSession();
		  session.beginTransaction();
		  session.save(user);    
          
          //提交事务    
          session.getTransaction().commit();  
          session.close();  
          }
		catch (Exception e){
			e.printStackTrace();    
            //回滚事务    
            session.getTransaction().rollback(); 
            session.close();  
            return false;
        }
		  return true;
		  	
	}
	

	public boolean doDelete(User user) throws Exception {
		try{
			session =HibernateUtil.getSession();
			  session.beginTransaction();
			  session.delete(user);    
	          
	          //提交事务    
	          session.getTransaction().commit();  
	          session.close();  
	          }
			catch (Exception e){
				e.printStackTrace();    
	            //回滚事务    
	            session.getTransaction().rollback(); 
	            session.close();  
	            return false;
	        }
			  return true;
			  				
	}
	
	public boolean doUpdate(User user) throws Exception {
		try{
			session =HibernateUtil.getSession();
			  session.beginTransaction();
			  session.update(user);    
	          
	          //提交事务    
	          session.getTransaction().commit();  
	          session.close();  
	          }
			catch (Exception e){
				e.printStackTrace();    
	            //回滚事务    
	            session.getTransaction().rollback(); 
	            session.close();  
	            return false;
	        }
			  return true;
			  
	}

	
	public List select(String id) throws Exception {
		 List<User> rs=null;
		try{
			session =HibernateUtil.getSession();
			  session.beginTransaction();
			  Query q = session.createSQLQuery("select * from user where id='"+id+"'").addEntity(User.class);
	          //提交事务    
			  rs = q.list(); 
	          session.close();  
	          }
			catch (Exception e){
				e.printStackTrace();    
	            session.close();  
	        }		
		return rs;
	}


	public List selectAll() throws Exception {
		 List<User> rs=null;
			try{
				session =HibernateUtil.getSession();
				  session.beginTransaction();
				  Query q = session.createSQLQuery("select * from user").addEntity(User.class);
		          //提交事务    
				  rs = q.list(); 
		          session.close();  
		          }
				catch (Exception e){
					e.printStackTrace();    
		            session.close();  
		        }		
			return rs;
		
	}
      
}


